package thread.ch04;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import thread.annotation.GuardBy;
import thread.annotation.ThreadSafe;

/**
 * 视图线程与更新线程会并发地访问数据模型，因此模型必须是线程安全的。
 * @author Edgar Zhang
 *
 */
@ThreadSafe
public class MonitorVehicleTracker {

	@GuardBy("this")
	private final Map<String, MutablePoint> locations;

	private MonitorVehicleTracker(Map<String, MutablePoint> locations) {
		this.locations = deepCopy(locations);
	}

	public synchronized Map<String, MutablePoint> getLocations() {
		return deepCopy(locations);
	}

	public synchronized MutablePoint getLocation(String key) {
		MutablePoint loc = locations.get(key);
		return loc == null ? null : new MutablePoint(loc);
	}

	public synchronized void setLocation(String id, int x, int y) {
		MutablePoint loc = locations.get(id);
		if (loc == null)
			throw new IllegalArgumentException("No such ID: " + id);
		loc.x = x;
		loc.y = y;
	}

	private static Map<String, MutablePoint> deepCopy(
			Map<String, MutablePoint> m) {
		Map<String, MutablePoint> result = new HashMap<String, MutablePoint>();
		for (String key : m.keySet()) {
			result.put(key, new MutablePoint(m.get(key)));
		}
		return Collections.unmodifiableMap(result);
	}

}
